<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style></style>
  </head>
  <body>
    <div>
      <h1>Proxy对比defineProperty</h1>
      <p>
        1.proxy更为强大,因为defineProperty只能监视属性的读写,Proxy能够监视到更多对象操作
      </p>
      <p>
        2.Proxy更好的支持数组对象的监视,以前defineProperty最常见的是方式是重写数组的操作方法
      </p>
      <p>
        3.Proxy是以非侵入的方式监管了对象的读写,不需要对对象本身进行操作,而Object.defineProperty需要对对象本身进行操作
      </p>
    </div>
    <script>
      const person = {
        name: "xjq",
        age: 20,
      };
      const personProxy = new Proxy(person, {
        //第一个参数代理的目标,第二个是要删除的属性名称
        deleteProperty(target, property) {
          console.log("delete", property); //delete age
          delete target[property];
        },
      });

      delete personProxy.age;
      console.log(person); //{name:'xjq'}

      //Proxy 对数组的监视
      const list = [];
      const listProxy = new Proxy(list, {
        set(target, property, value) {
          //这里的property下标是Proxy自动推算的
          console.log("set", property, value); //set 0 100
          target[property] = value;
          return true; // 表示设置成功
        },
      });

      listProxy.push(100);

      //Object.defineProperty
      const person1 = {};
      Object.defineProperty(person1, "name", {
        get() {
          console.log("name 被访问");
          return person1._name;
        },
        set(value) {
          console.log("name 被访问");
          person1._name = value;
        },
      });

      Object.defineProperty(person1, "age", {
        get() {
          console.log("age 被访问");
          return person1._age;
        },
        set(value) {
          console.log("age 被访问");
          person1._age = value;
        },
      });
      person1.name = "jack";
    </script>
  </body>
</html>
